import {Injectable} from '@angular/core';
import {Farm} from '../entity/farm.model';
import {Observable} from 'rxjs/Observable';
import {AppConfig} from '../config';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class FarmService {
  private readonly param = 'farms';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(
    private http: InterceptorService) {
  }

  getFarms(): Promise<Farm[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Farm[])
      .catch(this.handleError);
  }

  getFarmByfarmID(farmID: number): Promise<Farm[]> {
    return this.http.get(`${this.url} ${farmID}`)
      .toPromise()
      .then(response => response.data as Farm[])
      .catch(this.handleError);
  }

  getFarmsWithTotalTurbineByUserId(userId: number): Promise<Farm[]> {
    return this.http.get(`${this.url}/count/userId/${userId}`)
      .toPromise()
      .then(response => {
        return response.data as Farm[]
      })
      .catch(this.handleError);
  }

  create(Farm: Farm): Promise<Farm> {
    return this.http.post(this.url, JSON.stringify(Farm))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as Farm;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(farm: Farm): Promise<Farm> {
    const url = `${this.url}`;
    return this.http.put(url, JSON.stringify(farm))
      .toPromise()
      .then(() => farm)
      .catch(this.handleError);
  }


  /**
   * 更新风场坐标
   *
   * @param {{farmId:number;posx:number;posy:number}} pos
   * @returns {Promise<boolean>}
   * @memberof FarmService
   */
  updateFarmPos(pos: { farmId: number; posx: number; posy: number }): Promise<boolean> {
    const url = `${this.url}/pos`;
    return this.http.put(url, JSON.stringify(pos))
      .toPromise()
      .then(response => {
          let code = response.code;
          switch (code) {
            case '200':
              return true;
            case '-1':
              return false;
          }
        }
      )
      .catch(this.handleError);
  }


  //根据farmName判断是否已经存在
  hasFarmName(farmName: string, farmId: number): Observable<boolean> {
    const url = `${this.url}/farmName/${farmName}/farmId/${farmId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //根据farmCode判断是否已经存在
  hasFarmCode(farmCode: string, farmId: number): Observable<boolean> {

    const url = `${this.url}/farmCode/${farmCode}/farmId/${farmId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  //根据simpleCode判断是否已经存在
  hasSimpleCode(simpleCode: string, farmId: number): Observable<boolean> {
    const url = `${this.url}/simpleCode/${simpleCode}/farmId/${farmId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }


  /**
   batchDelete(valueIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${valueIds}`;
    return this.http.delete(apiUrl, { headers: this.headers })
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case "200":
              return true;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }
   */

  batchDelete(valueIds: number[]): Promise<any> {
    const apiUrl = `${this.url}?items=${valueIds}`;
    // const apiUrl = `http://192.168.15.3:8585/webapi/v1/farms?items=${valueIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return result;
            case '-1':
              throw new Error(result.message);
            case '8001':
              return result;
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }


  getFarmSweptDiameterByFarmId(valueIds: number[]): Promise<FarmSweptDiameter> {
    //const apiUrl = `http://192.168.15.3:8585/webapi/v1/farms/getModelMap?items=${valueIds}`;
    const apiUrl = `${this.url}/getModelMap?items=${valueIds}`;
    return this.http.get(apiUrl)
      .toPromise()
      .then(response => {
        return response.data as FarmSweptDiameter
      })
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }


}

export interface FarmSweptDiameter {
  [i: string]: SweptDiameter

}

interface SweptDiameter {
  farmId: number,
  modelId: number,
  bladeSindiaMeter: number
}


// WEBPACK FOOTER //
// ./src/app/service/farm.service.ts
